package com.collectplus.express.logic;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.widget.ImageView;

import com.collectplus.express.MainActivity;
import com.collectplus.express.R;
import com.collectplus.express.menu.WebViewActivity;
import com.collectplus.express.model.BannerBean;
import com.collectplus.express.model.CollectingPassportBean;
import com.collectplus.express.model.Const;
import com.collectplus.express.model.IdCardInfoBean;
import com.collectplus.express.model.PassportDetailBean;
import com.collectplus.express.passport.NewPassportCollectingActivity;
import com.collectplus.express.passport.NewPassportDialogActivity;
import com.shouhuobao.identity.AuthenticationActivity;
import com.shouhuobao.identity.VerificationResultsActivity;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.net.URISyntaxException;
import java.text.MessageFormat;

import droid.frame.activity.ActivityMgr;
import droid.frame.utils.android.Log;
import droid.frame.utils.http.BitmapUtils;
import droid.frame.utils.lang.Str;

/**
 * 数据库相关的操作
 *
 * @author coffee<br>
 * 2014-10-20上午10:06:44
 */
public class AppLogic {
    private static AppLogic instance;

    private AppLogic() {

    }

    public synchronized static AppLogic getInstance() {
        if (instance == null) {
            instance = new AppLogic();
        }
        return instance;
    }

    /**
     * 注意不能在listview中调用, 会导致图片错乱
     *
     * @param url       传入绝对路径
     * @param imageView
     */
    public void loadImage(final String url, final ImageView imageView) {
        // 默认检查本地缓存
        loadImage(url, imageView, true);
    }

    /**
     * @param url          传入绝对路径
     * @param isCheckLocal 是否检查本地缓存
     * @param imageView
     */
    public void loadImage(final String url, final ImageView imageView, final boolean isCheckLocal) {
        if (imageView == null) {
            Log.w("app:logic", "imageview为空, url不予请求", null);
            return;
        }
        // 头像
        new AsyncTask<Void, Void, Bitmap>() {
            @Override
            protected Bitmap doInBackground(Void... params) {
                // 头像
                Bitmap image = BitmapUtils.loadBitmapFromNet(url, isCheckLocal);
                return image;
            }

            @Override
            protected void onPostExecute(Bitmap result) {
                if (result != null && imageView != null) {
                    imageView.setImageBitmap(result);
                }
            }
        }.execute();
    }

    /**
     * 支付成功界面跳转
     */
    public void onPaySuccess(Activity context) {
        //这里不建议用增强for循环，之前使用增强for，发现栈里的没有清除干净，所以这里采用普通的倒序移除，符合栈的先进后出原理
        if (ActivityMgr.getAllActivitys() != null && ActivityMgr.getAllActivitys().size() > 0) {
            for (int i = ActivityMgr.getAllActivitys().size() - 1; i > 0; i--) {
                Activity activity = ActivityMgr.getAllActivitys().get(i);
                if (ActivityMgr.getAllActivitys().size() != 1) {
                    activity.finish();
                    ActivityMgr.remove(activity);
                }
            }
        }
        Intent intent = new Intent();
        intent.setClass(context, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        // intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        // intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
        Bundle bundle = new Bundle();
        bundle.putString("orderId", AppCache.getOrderId() + "");
        bundle.putString("userId", AppCache.getUserId() + "");
        bundle.putSerializable("order", AppCache.getOrder());
        bundle.putSerializable("parcelId", AppCache.getParcelId() + "");
        intent.putExtras(bundle);
        context.startActivity(intent);
        if (AppCache.getParcelNew() != null && AppCache.getParcelNew().getSender() != null) {
            AppCache.setSenderBean(AppCache.getParcelNew().getSender());
        }
        // 支付成功以后、清空parcel
        AppCache.setParcelNew(null);
        AppCache.setOrder(null);
    }

    /**
     * 跳转到passport详情页
     * @param context
     * @param passport
     * @param parcelId
     */
    //    public void showPassportDialog(Context context, PassportDetailBean passport, String parcelId) {
    //        Intent intent = new Intent();
    //        intent.setClass(context, PassportDetailsDialogActivity.class);
    //        intent.putExtra("parcelId", parcelId);
    //        intent.putExtra("item", passport);
    //        context.startActivity(intent);
    //    }

    /**
     * 跳转到passport滑动页
     *
     * @param context
     * @param parcelId
     */
//    public void showPassportDialog(Context context, String parcelId, ArrayList<PassportBean> passportBeans, int position) {
//        Intent intent = new Intent();
//        intent.setClass(context, NewPassportDialogActivity.class);
//        intent.putExtra("parcelId", parcelId);
//        intent.putExtra("position", position);
//        intent.putExtra("passportBeans", passportBeans);
//        context.startActivity(intent);
//    }
    public void showPassportDialog(Context context, PassportDetailBean passport, String parcelId) {
        Intent intent = new Intent();
        intent.setClass(context, NewPassportDialogActivity.class);
        intent.putExtra("parcelId", parcelId);
        intent.putExtra("item", passport);
        context.startActivity(intent);
    }

    public void showCollectingPassportDialog(Context context, CollectingPassportBean passport, String stationId, String takeId) {
        Intent intent = new Intent();
        intent.setClass(context, NewPassportCollectingActivity.class);
        intent.putExtra("stationId", stationId);
        intent.putExtra("takeId", takeId);
        intent.putExtra("item", passport);
        context.startActivity(intent);
    }

    /**
     * @param diff 时间差、单位毫秒
     * @return 返回 [时、分、秒]
     */
    public long[] timeDiff(long diff) {
        long diffSeconds = diff / 1000 % 60;
        long diffMinutes = diff / (60 * 1000) % 60;
        long diffHours = diff / (60 * 60 * 1000) % 24;
        // long diffDays = diff / (24 * 60 * 60 * 1000);
        droid.frame.utils.android.Log.d("diff", diffSeconds);
        return new long[]{diffHours, diffMinutes, diffSeconds};
    }

    /**
     * 参考{@link #timeDiff(long)} 时分秒-字符串格式化为两位数
     *
     * @param diff
     * @return
     */
    public String[] timeDiffStr(long diff) {
        long[] diffs = timeDiff(diff);
        String[] arr = new String[diffs.length];
        for (int i = 0; i < diffs.length; i++) {
            if (String.valueOf(diffs[i]).length() < 2) {
                arr[i] = "0" + diffs[i];
            } else {
                arr[i] = "" + diffs[i];
            }
        }
        return arr;
    }

    /**
     * 检查本地是否已经安装微信
     *
     * @param context
     * @return
     */
    public static boolean isInstallWXApp(Context context) {
        IWXAPI wxapi = WXAPIFactory.createWXAPI(context, null);
        if (wxapi.isWXAppInstalled() == false) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * @param latitude  维度
     * @param longitude 经度
     * @return
     */
    public Intent getBaiduIntentUri(Context context, String latitude, String longitude, String address) {
        Intent intent = null;

        String uri = null;
        // 导航

        // String format = "intent://map/direction?origin=latlng:{0},{1}" + //
        // "|name:我的位置&destination={2},{3}&mode=driving&region={4}" + //
        // "&src={5}#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end";
        // uri = MessageFormat.format(format, latitude, longitude, //
        // item.getLatitude(), item.getLongitude(), "beijing", context.getPackageName());

        String format = "intent://map/marker?location={0},{1}&title={2}&content={3}&src={4}" + //
                "#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end";
        uri = MessageFormat.format(format, latitude, longitude, "", address, context.getPackageName());

        try {
            intent = Intent.parseUri(uri, Intent.URI_INTENT_SCHEME);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }

        return intent;
    }

    /**
     * 格式化倒计时的文本显示
     *
     * @return
     */
    public SpannableString formatCountDown(Activity context, long diff, int parcelType) {
        String[] diffs = timeDiffStr(diff);
        String src = null;//
        SpannableString ss = null;
        int color = context.getResources().getColor(R.color.passport_11);
        if (parcelType == Const.ParcelType.bagToBox) {
            color = context.getResources().getColor(R.color.passport_21);
        }
        if (diffs.length == 3) {//
            src = diffs[0] + "小时" + diffs[1] + "分" + diffs[2] + "秒";
            ss = new SpannableString(src);
            int index1 = src.indexOf("小时");
            int index2 = src.indexOf("分");
            int index3 = src.indexOf("秒");
            ss.setSpan(new ForegroundColorSpan(color), 0, index1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            ss.setSpan(new RelativeSizeSpan(1.5F), 0, index1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
            // 注意index1 + (2) 2代表 字符串"小时"的长度
            ss.setSpan(new ForegroundColorSpan(color), index1 + 2, index2, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            ss.setSpan(new RelativeSizeSpan(1.5F), index1 + 2, index2, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
            //
            ss.setSpan(new ForegroundColorSpan(color), index2 + 1, index3, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            ss.setSpan(new RelativeSizeSpan(1.5F), index2 + 1, index3, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        }
        if (diffs.length == 2) {//
            src = diffs[0] + "分" + diffs[1];
            ss = new SpannableString(src);
            int index1 = src.indexOf("分");
            int index2 = src.indexOf("秒");
            ss.setSpan(new ForegroundColorSpan(color), 0, index1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            ss.setSpan(new RelativeSizeSpan(1.5F), 0, index1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
            //
            ss.setSpan(new ForegroundColorSpan(color), index1 + 1, index2, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            ss.setSpan(new RelativeSizeSpan(1.5F), index1 + 1, index2, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        }
        return ss;
    }

    /**
     * 处理banner数据跳转
     *
     * @param bannerBean
     */
    public static void disposeBannerData(Activity context, BannerBean bannerBean) {
        try {
            if (1 == bannerBean.getOpenType()) {
                if (!Str.isEmpty(bannerBean.getLink())) {
                    Intent intent = new Intent();
                    intent.setClass(context, WebViewActivity.class);
                    if (Str.isNotEmpty(bannerBean.getCity()) && AppCache.getCurrentCityName().startsWith(bannerBean.getCity())) {
                        intent.putExtra("title", "领取优惠券");
                        if (AppCache.isLogin() == false) {
                            intent.putExtra("url", bannerBean.getLink() + "?device=1&phone=");
                        } else {
                            intent.putExtra("url", bannerBean.getLink() + "?device=1&phone=" + AppCache.getUser().getPhone());
                        }
                    } else {
                        intent.putExtra("title", bannerBean.getTitle());
                        intent.putExtra("url", bannerBean.getLink());
                    }
                    //                        intent.putExtra("title", "领取优惠券");
                    //                        if (AppCache.isLogin() == false) {
                    //                            intent.putExtra("url", "http://10.100.0.148/guoer-appserv/static/promo/doubleEleven.html?&device=1&phone=");
                    //                        } else {
                    //                            intent.putExtra("url", "http://10.100.0.148/guoer-appserv/static/promo/doubleEleven.html?device=1&phone=" + AppCache.getUser().getPhone());
                    //                        }
                    context.startActivity(intent);
                }
            } else {
                if (!Str.isEmpty(bannerBean.getLink())) {
                    String activityName = bannerBean.getLink().split(";")[0];
                    if (!Str.isEmpty(activityName)) {
                        Intent intent = new Intent();
                        intent.setClassName(context, activityName);
                        context.startActivity(intent);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据身份认证信息跳转到不同的类
     */
    public static void contextToAuthenticationClass(Activity context, IdCardInfoBean cardInfoBean) {
        Intent intent = null;
        if (null == cardInfoBean) {
            intent = new Intent(context, AuthenticationActivity.class);
            context.startActivity(intent);
        } else {
            intent = new Intent(context, VerificationResultsActivity.class);
            intent.putExtra("bean", cardInfoBean);
            context.startActivity(intent);
        }
    }
}
